import React, { useState, useEffect } from 'react';
import { Popup, PickerView, Input } from 'antd-mobile';
import { RightOutline } from 'antd-mobile-icons';
import regionData from 'china-area-data';
import './Tdi.css';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import {tdi} from '../../https/index'

// 格式化地区数据
const formatRegionData = () => {
  // 将数据对象转换为选项数组
  const convertToOptions = (dataObj) => {
    if (typeof dataObj !== 'object' || dataObj === null || Array.isArray(dataObj)) {
      return [];
    }
    return Object.entries(dataObj)
      .filter(([value, label]) => typeof value === 'string' && typeof label === 'string')
      .map(([value, label]) => ({ label, value }));
  };

  // 获取省级数据
  const provinceData = regionData['86'] || {};
  const provinces = convertToOptions(provinceData);

  // 根据省份编码获取城市数据
  const getCitiesByProvince = (provinceCode) => {
    if (!provinceCode) return [];
    const cityData = regionData[provinceCode] || {};
    return convertToOptions(cityData);
  };

  // 根据城市编码获取区县数据
  const getDistrictsByCity = (cityCode) => {
    if (!cityCode) return [];
    const districtData = regionData[cityCode] || {};
    return convertToOptions(districtData);
  };

  return { provinces, getCitiesByProvince, getDistrictsByCity };
};

const { provinces, getCitiesByProvince, getDistrictsByCity } = formatRegionData();

const Tid = () => {
  // 导航对象
  const nav = useNavigate();

  // 省市区选择状态
  const [selectedProvince, setSelectedProvince] = useState('');
  const [selectedCity, setSelectedCity] = useState('');
  const [selectedDistrict, setSelectedDistrict] = useState('');
  const [columns, setColumns] = useState([provinces, [], []]);
  const [regionText, setRegionText] = useState('');
  const [visible1, setVisible1] = useState(false);

  // 表单数据状态
  const [recipient, setRecipient] = useState('');
  const [phone, setPhone] = useState('');
  const [detailAddress, setDetailAddress] = useState('');
  const [isDefault, setIsDefault] = useState(false);

  // 初始化根字体大小
  useEffect(() => {
    const setRootFontSize = () => {
      document.documentElement.style.fontSize = '10px';
    };
    setRootFontSize();
    window.addEventListener('resize', setRootFontSize);
    return () => window.removeEventListener('resize', setRootFontSize);
  }, []);

  // 省份选择变化时更新城市列表
  useEffect(() => {
    if (!selectedProvince) {
      setColumns([provinces, [], []]);
      setSelectedCity('');
      setSelectedDistrict('');
      return;
    }
    const cities = getCitiesByProvince(selectedProvince);
    const safeCities = Array.isArray(cities) ? cities : [];
    setColumns([provinces, safeCities, []]);
    setSelectedCity(safeCities.length > 0 ? safeCities[0].value : '');
  }, [selectedProvince]);

  // 城市选择变化时更新区县列表
  useEffect(() => {
    if (!selectedCity) {
      setColumns(prev => [prev[0], prev[1], []]);
      setSelectedDistrict('');
      return;
    }
    const districts = getDistrictsByCity(selectedCity);
    const safeDistricts = Array.isArray(districts) ? districts : [];
    setColumns(prev => [prev[0], prev[1], safeDistricts]);
    setSelectedDistrict(safeDistricts.length > 0 ? safeDistricts[0].value : '');
  }, [selectedCity]);

  // 处理省市区选择变化
  const handlePickerChange = (values) => {
    const [province, city, district] = values || [];
    setSelectedProvince(province || '');
    setSelectedCity(city || '');
    setSelectedDistrict(district || '');

    const provinceText = province ? regionData['86'][province] : '';
    const cityText = city ? regionData[province]?.[city] : '';
    const districtText = district ? regionData[city]?.[district] : '';
    setRegionText([provinceText, cityText, districtText].filter(Boolean).join('-'));
  };

  // 加密手机号的函数
  const encryptPhone = (phoneNumber) => {
    if (!phoneNumber) return '';
    // 检查手机号是否为11位
    if (phoneNumber.length !== 11) return phoneNumber;
    // 将中间四位替换为星号
    return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  };

  // 提交地址到后端
  const handleSaveAddress = async () => {
    if (!recipient || !phone || !regionText || !detailAddress) {
      alert('请填写完整地址信息');
      return;
    }

    // 加密手机号
    const encryptedPhone = encryptPhone(phone);
    console.log(encryptPhone);

const pid = sessionStorage.getItem('logid')
    const addressData = {
      recipient,
      phone: encryptedPhone, // 使用加密后的手机号
      provinceCode: selectedProvince,
      provinceName: regionData['86'][selectedProvince] || '',
      cityCode: selectedCity,
      cityName: regionData[selectedProvince]?.[selectedCity] || '',
      districtCode: selectedDistrict,
      districtName: regionData[selectedCity]?.[selectedDistrict] || '',
      detailAddress,
      isDefault: document.getElementById('default-address').checked,
      logId:pid
    };
console.log(addressData);

    try {
      const response = await tdi(addressData)
      console.log(response);

      if (response) {
        alert('地址保存成功');
      } else {
        alert('保存失败，请重试');
      }
    } catch (error) {
      console.error('请求错误:', error);
      alert('网络错误，请稍后重试');
    }
  };

  // 返回上一页
  const fan = () => {
    nav('/di');
  };

  return (
    <div style={{
      width: '100%',
      maxWidth: '50rem',
      margin: '0 auto',
      fontFamily: 'Arial, sans-serif',
      fontSize: '1.6rem'
    }}>
      <div style={{
        backgroundColor: '#e51c23',
        color: 'white',
        padding: '1rem',
        display: 'flex',
        alignItems: 'center'
      }}>
        <span style={{ fontSize: '2rem', marginRight: '14rem', cursor: 'pointer' }} onClick={fan}>&lt;</span>
        <span style={{ margin: '0', fontWeight: "bold" }}>添加地址</span>
      </div>

      <form style={{ padding: '2rem' }}>
        <div style={{ marginBottom: '2rem', display: "flex", alignItems: 'center' }}>
          <span style={{ fontWeight: 'bold', marginRight: "3rem" }}>收件人：</span>
          <Input
            placeholder='请输入收件人姓名'
            value={recipient}
            onChange={(v) => setRecipient(v)}
            style={{ flex: 1 }}
          />
        </div>

        <div style={{ marginBottom: '2rem', display: "flex", alignItems: 'center' }}>
          <span style={{ fontWeight: 'bold', marginRight: "1.4rem" }}>手机号码：</span>
          <Input
            placeholder='请输入收件人手机号'
            value={phone}
            onChange={(v) => setPhone(v)}
            style={{ flex: 1 }}
          />
        </div>

        <div style={{ marginBottom: '2rem', display: "flex", alignItems: 'center' }}>
          <span style={{ fontWeight: 'bold', marginRight: "1.3rem" }}>所在地区：</span>
          <div className='password' style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
            <Input
              className='input'
              placeholder='请选择'
              value={regionText}
              readOnly
              onClick={() => setVisible1(true)}
              style={{ flex: 1 }}
            />
            <div className='eye' onClick={() => setVisible1(true)}>
              <RightOutline />
            </div>
          </div>
        </div>

        <div style={{ marginBottom: '2rem', display: "flex", alignItems: 'center' }}>
          <span style={{ fontWeight: 'bold', marginRight: "1.3rem" }}>详细地址：</span>
          <Input
            placeholder='请填写详细地址'
            value={detailAddress}
            onChange={(v) => setDetailAddress(v)}
            style={{ flex: 1 }}
          />
        </div>

        <div style={{ marginBottom: '2rem', display: 'flex', alignItems: 'center' }}>
          <input
            type="checkbox"
            id="default-address"
            style={{ marginRight: '0.8rem', width: '1.6rem', height: '1.6rem' }}
            checked={isDefault}
            onChange={() => setIsDefault(!isDefault)}
          />
          <label htmlFor="default-address" style={{ fontSize: '1.6rem' }}>设为默认地址</label>
        </div>

        <button
          type="button"
          style={{
            width: '100%',
            padding: '1rem',
            backgroundColor: '#e51c23',
            color: 'white',
            border: 'none',
            borderRadius: '0.4rem',
            cursor: 'pointer',
            fontSize: '1.6rem'
          }}
          onClick={handleSaveAddress}
        >
          保存
        </button>
      </form>

      <Popup
        visible={visible1}
        onMaskClick={() => setVisible1(false)}
        onClose={() => setVisible1(false)}
        bodyStyle={{ height: '40vh' }}
      >
        <button style={{ marginRight: "33rem" }} onClick={() => setVisible1(false)}>取消</button>
        <button onClick={() => setVisible1(false)}>确定</button>
        <PickerView
          columns={columns}
          value={[selectedProvince, selectedCity, selectedDistrict]}
          onChange={handlePickerChange}
          mouseWheel={true}
        />
      </Popup>
    </div>
  );
};

export default Tid;